<template>
  <div class="admin-refund-page">
    <h2>退货退款管理</h2>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable @change="handleFilterChange">
            <el-option label="待处理" value="pending" />
            <el-option label="已同意" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadRefunds">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 退货记录列表 -->
    <div v-loading="loading" class="refunds-list">
      <el-empty v-if="!loading && refunds.length === 0" description="暂无退货记录" />
      
      <div v-for="refund in refunds" :key="refund.id" class="refund-card">
        <div class="refund-header">
          <div>
            <span class="order-no">订单号：{{ refund.orderNo }}</span>
            <span class="customer-name">顾客：{{ refund.name }}（{{ refund.username }}）</span>
          </div>
          <el-tag :type="getStatusType(refund.status)">{{ getStatusText(refund.status) }}</el-tag>
        </div>
        
        <div class="refund-content">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="info-item">
                <span class="label">退款金额：</span>
                <span class="value amount">¥{{ refund.refundAmount }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(refund.createTime) }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="label">顾客电话：</span>
                <span class="value">{{ refund.order?.phone || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="label">支付方式：</span>
                <span class="value">{{ getPaymentMethodText(refund.order?.paymentMethod) }}</span>
              </div>
            </el-col>
          </el-row>
          
          <div class="info-item">
            <span class="label">退货原因：</span>
            <span class="value">{{ refund.refundReason }}</span>
          </div>
          
          <div v-if="refund.handleTime" class="info-item">
            <span class="label">处理人：</span>
            <span class="value">{{ refund.handlerName || '暂无' }}</span>
          </div>
          
          <div v-if="refund.handleTime" class="info-item">
            <span class="label">处理时间：</span>
            <span class="value">{{ formatDate(refund.handleTime) }}</span>
          </div>
          
          <div v-if="refund.handleRemark" class="info-item">
            <span class="label">处理备注：</span>
            <span class="value">{{ refund.handleRemark }}</span>
          </div>
        </div>
        
        <div class="refund-footer">
          <el-button 
            v-if="refund.status === 'pending'" 
            type="success" 
            size="small" 
            @click="handleRefund(refund, 'approved')">
            同意退货
          </el-button>
          <el-button 
            v-if="refund.status === 'pending'" 
            type="danger" 
            size="small" 
            @click="handleRefund(refund, 'rejected')">
            拒绝退货
          </el-button>
          <el-button type="primary" size="small" plain @click="viewOrderDetail(refund)">
            查看订单
          </el-button>
          <el-button type="info" size="small" plain @click="viewRefundDetail(refund)">
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 处理退货对话框 -->
    <el-dialog v-model="handleDialogVisible" :title="handleTitle" width="600px">
      <el-form :model="handleForm" :rules="handleRules" ref="handleFormRef" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="currentRefund.orderNo" disabled />
        </el-form-item>
        <el-form-item label="顾客">
          <el-input :value="`${currentRefund.name}（${currentRefund.username}）`" disabled />
        </el-form-item>
        <el-form-item label="退款金额">
          <el-input v-model="currentRefund.refundAmount" disabled>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="退货原因">
          <el-input v-model="currentRefund.refundReason" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item label="处理备注" prop="handleRemark">
          <el-input
            v-model="handleForm.handleRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitHandle">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="退货详情" width="700px">
      <div v-if="currentRefund.id" class="refund-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退货ID">{{ currentRefund.id }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ currentRefund.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="顾客">{{ currentRefund.name }}（{{ currentRefund.username }}）</el-descriptions-item>
          <el-descriptions-item label="退款金额">
            <span class="amount">¥{{ currentRefund.refundAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(currentRefund.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRefund.status)">{{ getStatusText(currentRefund.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="退货原因" :span="2">{{ currentRefund.refundReason }}</el-descriptions-item>
          <el-descriptions-item v-if="currentRefund.handleTime" label="处理人">
            {{ currentRefund.handlerName || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRefund.handleTime" label="处理时间">
            {{ formatDate(currentRefund.handleTime) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRefund.handleRemark" label="处理备注" :span="2">
            {{ currentRefund.handleRemark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRefundList, handleRefund as handleRefundApi } from '@/api/refund'
import { useRouter } from 'vue-router'

const router = useRouter()

const loading = ref(false)
const refunds = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filterForm = ref({
  status: ''
})

const handleDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentRefund = ref({})
const handleForm = ref({
  status: '',
  handleRemark: ''
})
const handleFormRef = ref(null)
const submitting = ref(false)

const handleRules = {
  handleRemark: [
    { max: 200, message: '处理备注不能超过200个字符', trigger: 'blur' }
  ]
}

const handleTitle = computed(() => {
  return handleForm.value.status === 'completed' ? '同意退货' : '拒绝退货'
})

// 加载退货记录列表
const loadRefunds = async () => {
  loading.value = true
  try {
    const res = await getRefundList({
      page: currentPage.value,
      pageSize: pageSize.value,
      status: filterForm.value.status
    })
    if (res.code === 200) {
      refunds.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '加载退货记录失败')
    }
  } catch (error) {
    console.error('加载退货记录失败', error)
    ElMessage.error('加载退货记录失败')
  } finally {
    loading.value = false
  }
}

// 筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
  loadRefunds()
}

// 重置筛选
const handleReset = () => {
  filterForm.value = {
    status: ''
  }
  currentPage.value = 1
  loadRefunds()
}

// 分页变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadRefunds()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadRefunds()
}

// 处理退货
const handleRefund = (refund, status) => {
  currentRefund.value = refund
  handleForm.value = {
    // 同意退货时直接设为completed状态，因为会立即完成退款
    status: status === 'approved' ? 'completed' : status,
    handleRemark: ''
  }
  handleDialogVisible.value = true
}

// 提交处理
const submitHandle = async () => {
  if (!handleFormRef.value) return
  
  await handleFormRef.value.validate(async (valid) => {
    if (valid) {
      const message = handleForm.value.status === 'completed' 
        ? '确定同意这个退货申请吗？退款将退回原支付方式。' 
        : '确定拒绝这个退货申请吗？'
      
      ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        submitting.value = true
        try {
          const res = await handleRefundApi(currentRefund.value.id, handleForm.value)
          if (res.code === 200) {
            ElMessage.success(res.message || '处理成功')
            handleDialogVisible.value = false
            loadRefunds()
          } else {
            ElMessage.error(res.message || '处理失败')
          }
        } catch (error) {
          console.error('处理退货失败', error)
          ElMessage.error('处理退货失败')
        } finally {
          submitting.value = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    }
  })
}

// 查看订单详情
const viewOrderDetail = (refund) => {
  router.push(`/admin/orders/${refund.orderId}`)
}

// 查看退货详情
const viewRefundDetail = (refund) => {
  currentRefund.value = refund
  detailDialogVisible.value = true
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'success'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待处理',
    approved: '已同意',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return textMap[status] || status
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const textMap = {
    cash: '现金',
    alipay: '支付宝',
    wechat: '微信'
  }
  return textMap[method] || method || '暂无'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadRefunds()
})
</script>

<style scoped lang="scss">
.admin-refund-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .refunds-list {
    .refund-card {
      margin-bottom: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .refund-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        background: #f7f8fa;
        border-bottom: 1px solid #ebeef5;

        .order-no {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
          margin-right: 20px;
        }

        .customer-name {
          font-size: 14px;
          color: #909399;
        }
      }

      .refund-content {
        padding: 20px;

        .info-item {
          margin-bottom: 12px;
          font-size: 14px;
          line-height: 1.8;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            color: #909399;
            margin-right: 10px;
          }

          .value {
            color: #303133;

            &.amount {
              color: #f56c6c;
              font-size: 18px;
              font-weight: bold;
            }
          }
        }
      }

      .refund-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        padding: 15px 20px;
        background: #f7f8fa;
        border-top: 1px solid #ebeef5;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .refund-detail {
    .amount {
      color: #f56c6c;
      font-size: 18px;
      font-weight: bold;
    }
  }
}
</style>


